import { getUserInfo } from "../../api/my";
import {
	USER_INFO,
	TOKEN,
	CONFIG
} from '@/config/cachekey';
import Cache from "../../utils/cache";

const state = {
	userInfo: {
		avatar: '',
		nickname: '',
		sn_num: 0,
	},
	token: Cache.get(TOKEN) || null,
	isBind: false
}


const mutations = {
	LOGIN(state, opt) {
		console.log("这是opt.token", opt.token)
		state.token = opt.token;
		Cache.set(TOKEN, opt.token, 59 * 24 * 60 * 60);
		this.dispatch('getUser')

	},
	LOGOUT(state) {
		state.token = undefined;
		state.userInfo = {
			avatar: '',
			nickname: '',
			sn_num: 0,
		}
		state.isBind = false
		Cache.remove(TOKEN);
		uni.clearStorageSync()
	},
	SETUSERINFO(state, userInfo) {
		state.userInfo = userInfo
		uni.setStorageSync('userId', userInfo.id)
	},
	SETBIND(state, status) {
		state.isBind = status
	}
}

const actions = {
	getUser({
		state,
		commit
	}) {
		return new Promise(resolve => {
			getUserInfo().then(res => {
				if (res.code == 200) {
					console.log("这是获取到的userInfo", res.data)
					commit('SETUSERINFO', res.data)
					let isBind = res.data.sn.length > 1 ? true : false
					commit('SETBIND', isBind)
				}else if (res.code == 10200) {
					commit('LOGOUT')
				}
			})
		})
	}
}

export default {
	state,
	mutations,
	actions
};